package com.vilen.weixin.service;

import com.vilen.basic.util.JsonUtil;
import com.vilen.weixin.kit.WeixinBasicKit;
import com.vilen.weixin.model.WUser;
import com.vilen.weixin.model.WeixinFinalValue;
import com.vilen.weixin.web.servlet.WeixinContext;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * Created by Administrator on 2016/2/18.
 */
@Service("wUserService")
public class WUserService implements IWUserService{
    @Override
    public WUser queryByOpenid(String openid) {
        String url = WeixinBasicKit.replaceAccessTokenUrl(WeixinFinalValue.USER_QUERY);
        url = url.replace("OPENID",openid);
        String json = WeixinBasicKit.sendGet(url);
        return (WUser) JsonUtil.getInstance().json2obj(json,WUser.class);
    }

    @Override
    public String queryOpenidByCode(String code) {
        String url = WeixinFinalValue.AUTH_GET_OID;
        url = url.replace("APPID", WeixinContext.getInstance().getAppId())
                .replace("SECRET",WeixinContext.getInstance().getAppSecret())
                .replace("CODE",code);
        String json = WeixinBasicKit.sendGet(url);
        //sring 到 tree
        try {
            String openid = JsonUtil.getMapper().readTree(json).get("openid").asText();
            return openid;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
